package com.study_online.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.study_online.config.AliPayConfig;
import com.study_online.domain.AliPay;
import com.study_online.domain.Order;
import com.study_online.domain.ResultInfo;
import com.study_online.mapper.OrderMapper;
import com.study_online.utils.AliPayUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 张天霸
 */
@RestController
@RequestMapping("/alipay")
public class AliPayController {

    @Autowired
    private OrderController orderController;

    /**
     * 付款接口
     * @param aliPay
     * @param httpResponse
     * @throws Exception
     */
    @RequestMapping("/pay") // subject=xxx&totalAmount=xxx
    public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {
//        AliPayConfig aliPayConfig = AliPayConfig.getInstance();
        //添加订单 begin
        Order order = new Order();
        order.setOrderName(aliPay.getSubject());
        order.setOrderMoney(aliPay.getTotalAmount());
        ResultInfo info = orderController.insert(order);
        //添加订单 end

        //得到订单号并赋给aliPay实体类 begin
        Order data = (Order)info.getData();
        aliPay.setTraceNo(data.getOrderNum());
        //得到订单号并赋给aliPay实体类 end

        Config config = AliPayUtils.outAliPay(); //通过工具类得到配置好的config
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do", config.appId,
                config.merchantPrivateKey, "JSON", "utf-8", config.alipayPublicKey, "RSA2");
//        AlipayClient alipayClient = new DefaultAlipayClient(aliPayConfig.getAppId(),
//                aliPayConfig.getAppPrivateKey(), aliPayConfig.getAlipayPublicKey());
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(config.notifyUrl);
        request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
                + "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
                + "\"subject\":\"" + aliPay.getSubject() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=utf-8");
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    /**
     *  异步回调接口
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String orderNum = params.get("out_trade_no");
            String payTime = params.get("gmt_payment");
            String alipayNum = params.get("trade_no");
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                // 更新订单为已支付
                orderController.updateStatus(orderNum,payTime,alipayNum);
//                ordersMapper.updateState(tradeNo, "已支付", gmtPayment, alipayTradeNo);
            }
        }
        return "success";
    }

}